import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  RefreshControl,
  TouchableOpacity
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { BlurView } from 'expo-blur';
import { Ionicons } from '@expo/vector-icons';
import { useAuth } from '../contexts/AuthContext';
import { userAPI, transactionAPI } from '../utils/api';
import { theme } from '../styles/theme';

const BalanceScreen = ({ navigation }) => {
  const { user } = useAuth();
  const [balance, setBalance] = useState(null);
  const [recentTransactions, setRecentTransactions] = useState([]);
  const [refreshing, setRefreshing] = useState(false);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const [balanceRes, transactionsRes] = await Promise.all([
        userAPI.getBalance(user.id),
        transactionAPI.getUserTransactions(user.id, { limit: 5 })
      ]);

      if (balanceRes.success) {
        setBalance(balanceRes.data.balance);
      }
      if (transactionsRes.success) {
        setRecentTransactions(transactionsRes.data.transactions);
      }
    } catch (error) {
      console.error('Fetch data error:', error);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    await fetchData();
    setRefreshing(false);
  };

  return (
    <LinearGradient colors={['#000000', '#1a1a1a']} style={styles.container}>
      {/* 头部 */}
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <Ionicons name="arrow-back" size={24} color={theme.colors.text} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>余额查询</Text>
        <View style={{ width: 24 }} />
      </View>

      <ScrollView
        contentContainerStyle={styles.scrollContent}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
      >
        {/* 余额卡片 */}
        <BlurView intensity={30} tint="dark" style={styles.balanceCard}>
          <LinearGradient
            colors={theme.gradients.gold}
            style={styles.balanceGradient}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
          >
            <View style={styles.balanceContent}>
              <Ionicons name="wallet" size={48} color="#000" style={styles.balanceIcon} />
              <Text style={styles.balanceLabel}>当前余额</Text>
              <Text style={styles.balanceAmount}>
                ¥{balance !== null ? parseFloat(balance).toFixed(2) : '---'}
              </Text>
              <View style={styles.balanceBadge}>
                <Ionicons name="shield-checkmark" size={16} color="#000" />
                <Text style={styles.badgeText}>已认证</Text>
              </View>
            </View>
          </LinearGradient>
        </BlurView>

        {/* 快捷操作 */}
        <View style={styles.actionsContainer}>
          <TouchableOpacity style={styles.actionButton} activeOpacity={0.8}>
            <BlurView intensity={20} tint="dark" style={styles.actionBlur}>
              <Ionicons name="add-circle-outline" size={32} color={theme.colors.primary} />
              <Text style={styles.actionText}>充值</Text>
            </BlurView>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.actionButton}
            activeOpacity={0.8}
            onPress={() => navigation.navigate('Transactions')}
          >
            <BlurView intensity={20} tint="dark" style={styles.actionBlur}>
              <Ionicons name="receipt-outline" size={32} color={theme.colors.primary} />
              <Text style={styles.actionText}>明细</Text>
            </BlurView>
          </TouchableOpacity>
        </View>

        {/* 最近交易 */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>最近交易</Text>
            <TouchableOpacity onPress={() => navigation.navigate('Transactions')}>
              <Text style={styles.sectionMore}>查看全部</Text>
            </TouchableOpacity>
          </View>

          {recentTransactions.map((item) => (
            <BlurView key={item.id} intensity={15} tint="dark" style={styles.transactionItem}>
              <View style={styles.transactionLeft}>
                <View
                  style={[
                    styles.transactionIcon,
                    { backgroundColor: item.type === 'recharge' ? theme.colors.success + '30' : theme.colors.warning + '30' }
                  ]}
                >
                  <Ionicons
                    name={item.type === 'recharge' ? 'arrow-down' : 'arrow-up'}
                    size={20}
                    color={item.type === 'recharge' ? theme.colors.success : theme.colors.warning}
                  />
                </View>
                <View>
                  <Text style={styles.transactionType}>
                    {item.type === 'recharge' ? '充值' : '消费'}
                  </Text>
                  <Text style={styles.transactionDate}>
                    {new Date(item.createdAt).toLocaleString('zh-CN')}
                  </Text>
                </View>
              </View>
              <Text
                style={[
                  styles.transactionAmount,
                  { color: item.type === 'recharge' ? theme.colors.success : theme.colors.warning }
                ]}
              >
                {item.type === 'recharge' ? '+' : '-'}¥{parseFloat(item.amount).toFixed(2)}
              </Text>
            </BlurView>
          ))}
        </View>
      </ScrollView>
    </LinearGradient>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: theme.spacing.lg,
    paddingTop: theme.spacing.xxl,
    paddingBottom: theme.spacing.md
  },
  headerTitle: {
    fontSize: theme.fontSizes.xlarge,
    fontWeight: 'bold',
    color: theme.colors.text
  },
  scrollContent: {
    padding: theme.spacing.lg,
    paddingTop: 0
  },
  balanceCard: {
    borderRadius: theme.borderRadius.large,
    overflow: 'hidden',
    marginBottom: theme.spacing.lg,
    borderWidth: 1,
    borderColor: theme.colors.border
  },
  balanceGradient: {
    padding: theme.spacing.xl,
    minHeight: 220
  },
  balanceContent: {
    alignItems: 'center'
  },
  balanceIcon: {
    marginBottom: theme.spacing.md,
    opacity: 0.8
  },
  balanceLabel: {
    fontSize: theme.fontSizes.medium,
    color: '#000',
    opacity: 0.8,
    marginBottom: theme.spacing.sm
  },
  balanceAmount: {
    fontSize: 48,
    fontWeight: 'bold',
    color: '#000',
    letterSpacing: 2,
    marginBottom: theme.spacing.md
  },
  balanceBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.2)',
    paddingHorizontal: theme.spacing.md,
    paddingVertical: theme.spacing.xs,
    borderRadius: theme.borderRadius.round,
    gap: theme.spacing.xs
  },
  badgeText: {
    fontSize: theme.fontSizes.small,
    color: '#000',
    fontWeight: '600'
  },
  actionsContainer: {
    flexDirection: 'row',
    gap: theme.spacing.md,
    marginBottom: theme.spacing.xl
  },
  actionButton: {
    flex: 1
  },
  actionBlur: {
    borderRadius: theme.borderRadius.medium,
    padding: theme.spacing.lg,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: theme.colors.border
  },
  actionText: {
    marginTop: theme.spacing.sm,
    fontSize: theme.fontSizes.medium,
    color: theme.colors.text
  },
  section: {
    marginBottom: theme.spacing.xl
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: theme.spacing.md
  },
  sectionTitle: {
    fontSize: theme.fontSizes.large,
    fontWeight: 'bold',
    color: theme.colors.text
  },
  sectionMore: {
    fontSize: theme.fontSizes.medium,
    color: theme.colors.primary
  },
  transactionItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: theme.spacing.md,
    borderRadius: theme.borderRadius.medium,
    marginBottom: theme.spacing.sm,
    borderWidth: 1,
    borderColor: theme.colors.border
  },
  transactionLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: theme.spacing.md
  },
  transactionIcon: {
    width: 40,
    height: 40,
    borderRadius: theme.borderRadius.small,
    alignItems: 'center',
    justifyContent: 'center'
  },
  transactionType: {
    fontSize: theme.fontSizes.medium,
    color: theme.colors.text,
    fontWeight: '600'
  },
  transactionDate: {
    fontSize: theme.fontSizes.small,
    color: theme.colors.textSecondary,
    marginTop: 2
  },
  transactionAmount: {
    fontSize: theme.fontSizes.large,
    fontWeight: 'bold'
  }
});

export default BalanceScreen;
